﻿using NextInventory.Model.Inventory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NextInventory.Business.EntityRepositories;
using MvcJqGrid;
using NextInventory.Model.Menufacturer;

namespace NextInventory.Web.Controllers
{
    [Authorize]
    public class InventoryController : Controller
    {
        private IInventoryRepository _inventory;
        private IMenufacturerRepository _menufacturer;
        public InventoryController(IInventoryRepository inventory, IMenufacturerRepository menufacturer)
        {
            _inventory = inventory;
            _menufacturer = menufacturer;
        }

        public ActionResult Index()
        {
            return View();
        }

        #region Category

        public ActionResult Categories()
        {
            return View();
        }

        public JsonResult CategoryGrid(GridSettings gridSettings)
        {
            int totalRecords;
            CategoryModel filter = new CategoryModel();
            if (gridSettings.IsSearch)
            {
                filter.Name = gridSettings.Where.rules.Any(r => r.field == "Name") ?
                        gridSettings.Where.rules.FirstOrDefault(r => r.field == "Name").data : string.Empty;
                filter.Description = gridSettings.Where.rules.Any(r => r.field == "Description") ?
                        gridSettings.Where.rules.FirstOrDefault(r => r.field == "Description").data : string.Empty;

            }
            var category = _inventory.SearchCategories(filter,
                                              gridSettings.SortColumn,
                                              gridSettings.SortOrder,
                                              gridSettings.PageSize,
                                              gridSettings.PageIndex,
                                              out totalRecords);
            var totalCount = category.Count();

            var jsonData = new
            {
                total = totalCount / gridSettings.PageSize + 1,
                page = gridSettings.PageIndex,
                records = totalCount,
                rows = (
                         from c in category
                         select new
                         {
                             ID = c.CategoryId,
                             Name = c.Name,
                             Description = c.Description
                         }
                             )
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult CategoryDetails(int? id)
        {
            return PartialView(id.HasValue ? _inventory.GetCategoryByID(id.Value) : new CategoryModel());
        }

        [HttpPost]
        public ActionResult CategoryDetails(CategoryModel model)
        {
            string message = string.Empty;
            var errors = ModelState.Values.SelectMany(v => v.Errors);
            if (ModelState.IsValid)
            {
                if (model.CategoryId == 0 ? _inventory.AddCategory(model, out message) : _inventory.UpdateCategory(model, out message))
                {
                    return RedirectToAction("Categories", "Inventory");
                }
                else
                {
                    ModelState.AddModelError("", message);
                }
            }

            return PartialView(model);
        }

        public ActionResult DeleteCategory(int id)
        {
            string message = string.Empty;
            if (_inventory.DeleteCategory(id, out message))
            {
                return RedirectToAction("Categories", "Inventory");
            }
            return View();
        }

        public JsonResult CategoryNameAvailable(string name)
        {
            string categoryNameAvailable = _inventory.CategoryNameAvailability(name);

            return Json(categoryNameAvailable, JsonRequestBehavior.AllowGet);
        }

        #endregion Category

        #region Model

        #region  Create Model

        [HttpGet]
        public ActionResult ModelDetails(int? id)
        {
            return PartialView(id.HasValue ? _inventory.GetProductModelByID(id.Value) : new ModelModel());
        }
        [HttpPost]
        public ActionResult ModelDetails(ModelModel model)
        {
            string message = string.Empty;
            if (ModelState.IsValid)
            {
                if (model.ModelId == 0 ? _inventory.AddProductModel(model, out message) : _inventory.UpdateProductModel(model, out message))
                {
                    return RedirectToAction("Categories", "Inventory");
                }
                else
                {
                    ModelState.AddModelError("", message);
                }
            }

            return PartialView(model);
        }

        #endregion  Create Model

        #region  Delete Model

        public ActionResult DeleteProductModel()
        {
            return View();
        }

        [Authorize]
        [HttpPost]

        public ActionResult DeleteProductModel(int id)
        {
            if (_inventory.DeleteProductModel(id))
            {
                return RedirectToAction("SearchModel", "Inventory");
            }
            return View();
        }

        #endregion   Create  Model

        #region  Search Model

        public ActionResult Models()
        {
            return View();
        }

        public JsonResult ModelGrid(GridSettings gridSettings)
        {
            int totalRecords;
            ModelModel filter = new ModelModel();
            if (gridSettings.IsSearch)
            {
                filter.Name = gridSettings.Where.rules.Any(r => r.field == "Name") ?
                        gridSettings.Where.rules.FirstOrDefault(r => r.field == "Name").data : string.Empty;
                filter.Description = gridSettings.Where.rules.Any(r => r.field == "Description") ?
                        gridSettings.Where.rules.FirstOrDefault(r => r.field == "Description").data : string.Empty;

            }
            var model = _inventory.SearchModels(filter,
                                              gridSettings.SortColumn,
                                              gridSettings.SortOrder,
                                              gridSettings.PageSize,
                                              gridSettings.PageIndex,
                                              out totalRecords);
            var totalCount = model.Count();

            var jsonData = new
            {
                total = totalCount / gridSettings.PageSize + 1,
                page = gridSettings.PageIndex,
                records = totalCount,
                rows = (
                                           from m in model
                                           select new
                                           {
                                               ID = m.ModelId,
                                               Name = m.Name,
                                               Description = m.Description,
                                               IsActive = m.IsActive,
                                               CreateBy = m.CreatedBy,
                                               CreatedDate = m.CreatedDate.ToString("dd-MM-yyyy"),
                                               UpdatedBy = m.UpdatedBy,
                                               // UpdatedDate = m.UpdatedDate.ToString("dd-MM-yyyy")
                                               UpdatedDate = m.UpdatedDate.ToString("dd-MM-yyyy")

                                           }
                                           )
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }


        #endregion  Search Model

        #endregion  Model

        #region Products

        public ActionResult Products()
        {
            return View();
        }

        public JsonResult ProductGrid(GridSettings gridSettings)
        {
            List<ProductsModel> product = null;
            int totalRecords;
            ProductsModel filter = new ProductsModel();
            if (gridSettings.IsSearch)
            {
                filter.Name = gridSettings.Where.rules.Any(r => r.field == "Name") ?
                        gridSettings.Where.rules.FirstOrDefault(r => r.field == "Name").data : string.Empty;
                filter.Description = gridSettings.Where.rules.Any(r => r.field == "Description") ?
                        gridSettings.Where.rules.FirstOrDefault(r => r.field == "Description").data : string.Empty;
                filter.ExpiryDate = gridSettings.Where.rules.Any(r => r.field == "ExpiryDate") ?
                        DateTime.ParseExact(gridSettings.Where.rules.FirstOrDefault(r => r.field == "ExpiryDate").data,
                                            "yyyy-MM-dd", null) : DateTime.MinValue;
                filter.PurchaseDate = gridSettings.Where.rules.Any(r => r.field == "PurchaseDate") ?
                       DateTime.ParseExact(gridSettings.Where.rules.FirstOrDefault(r => r.field == "PurchaseDate").data,
                                           "yyyy-MM-dd", null) : DateTime.MinValue;
            }

            product = _inventory.SearchProducts(filter,
                                                  gridSettings.SortColumn,
                                                  gridSettings.SortOrder,
                                                  gridSettings.PageSize,
                                                  gridSettings.PageIndex,
                                                  out totalRecords);

            var jsonData = new
            {
                total = totalRecords / gridSettings.PageSize + 1,
                page = gridSettings.PageIndex,
                records = totalRecords,
                rows = (
                            from p in product
                            select new
                            {
                                ID = p.ID,
                                Name = p.Name,
                                Description = p.Description,
                                ExpiryDate = p.ExpiryDate,
                                PurchaseDate = p.PurchaseDate,
                                PurchaseRate = p.PurchaseRate,
                                MenuFacturingDate = p.MenuFacturingDate,
                                OpeningQty = p.OpeningQty,
                                OpeningValue = p.OpeningValue,
                                SaleRate = p.SaleRate,
                                CategoryId = p.CategoryId,
                                ModelId = p.ModelId,
                                MenufacturerId = p.MenufacturerId,
                                CreateBy = p.CreatedBy,
                                CreatedDate = p.CreatedDate,
                                UpdatedBy = p.UpdatedBy,
                                // UpdatedDate = m.UpdatedDate.ToString("dd-MM-yyyy")
                                UpdatedDate = p.UpdatedDate
                            }
                            )
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ProductDetails(int? id)
        {
            List<CategoryModel> Categories = new List<CategoryModel>();
            List<MenufacturerModel> Menufacturers = new List<MenufacturerModel>();
            List<ModelModel> Models = new List<ModelModel>();

            Categories = _inventory.GetAllCategories();
            Menufacturers = _menufacturer.SearchMenufacturer();
            Models = _inventory.GetAllModels();

            ViewBag.Categories = Categories;
            ViewBag.Menufacturers = Menufacturers;
            ViewBag.Models = Models;

            return View(id.HasValue ? _inventory.GetProductByID(id.Value) : new ProductsModel());
        }

        [HttpPost]
        public ActionResult ProductDetails(ProductsModel model)
        {
            bool isSuccess;
            if (ModelState.IsValid)
            {
                if (model.ID == 0)
                {
                    isSuccess = _inventory.AddProduct(model);
                    if (isSuccess)
                    {
                        TempData["message"] = "";
                        ModelState.Clear();
                        return RedirectToAction("Products", "Inventory");
                    }
                }
                else
                {
                    isSuccess = _inventory.UpdateProduct(model);
                    if (isSuccess)
                    {
                        TempData["message"] = "";
                        ModelState.Clear();
                        return RedirectToAction("Products", "Inventory");
                    }
                }
            }

            List<CategoryModel> Categories = new List<CategoryModel>();
            List<MenufacturerModel> Menufacturers = new List<MenufacturerModel>();
            List<ModelModel> Models = new List<ModelModel>();

            Categories = _inventory.GetAllCategories();
            Menufacturers = _menufacturer.SearchMenufacturer();
            Models = _inventory.GetAllModels();

            ViewBag.Categories = Categories;
            ViewBag.Menufacturers = Menufacturers;
            ViewBag.Models = Models;

            return View(model);
        }

        public ActionResult DeleteProduct(int id)
        {
            if (_inventory.DeleteProduct(id))
            {
                return RedirectToAction("Products", "Inventory");
            }
            return View();
        }

        #endregion Products

    }
}
